package com.shuma.approval.aspect;

import com.shuma.approval.annotation.DefaultRemark;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DefaultRemarkAspect {

    @Around("@annotation(com.shuma.approval.annotation.DefaultRemark)")
    public Object handleDefaultRemark(JoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DefaultRemark defaultRemark = method.getAnnotation(DefaultRemark.class);

        Object[] args = joinPoint.getArgs();
        String[] parameterNames = signature.getParameterNames();
        for (int i = 0; i < parameterNames.length; i++) {
            if ("remark".equals(parameterNames[i]) && (args[i] == null || args[i].toString().isEmpty())) {
                args[i] = defaultRemark.value();
            }
        }

        return ((org.aspectj.lang.ProceedingJoinPoint) joinPoint).proceed(args);
    }
}
